package com.base.cn.platform.os.common.mybatis.table;

import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 创建表工具类
 *
 * @author s.li
 * @date 2019/04/12
 */
@Slf4j
public class CreateTableTool {

    /**
     * 创建表
     * @param dataSource 数据源
     * @param tableNameSuffixMap 表数据，KEY=表名，VALUE=表的后缀
     */
    public static synchronized void createTable(DataSource dataSource, Map<String,String> tableNameSuffixMap){
        Connection connection =null;
        Statement statement = null;
        try {
            connection = dataSource.getConnection();
            statement = connection.createStatement();
            Set<String> keySet = tableNameSuffixMap.keySet();
            Iterator<String> it = keySet.iterator();
            String databaseName = connection.getSchema();
            while (it.hasNext()){
                String tableName = it.next();
                log.info("-------------------databaseName : "+databaseName+"==>"+tableName);
                String suffix = tableNameSuffixMap.get(tableName);
                String newTableName =  "`"+tableName+"_"+suffix+"`";
                ResultSet createTbSqlSet = statement.executeQuery("show create table "+ tableName+";");
                if (createTbSqlSet.next()){
                    try {
                        String createTbSql = createTbSqlSet.getString(2).replace("`"+tableName+"`",newTableName);
                        createTbSqlSet.close();
                        statement.executeUpdate(createTbSql);
                    }catch (Exception es){
                        log.error("---------error "+es.getMessage());
                    }
                }
            }
        }catch (Exception e) {
            log.error("--------------connection.close() create table error "+e.getMessage());
        }finally {
            try {
                if(statement!=null){
                    statement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException e) {
                log.error("--------------:finally run createTable() create table error "+e.getMessage());
            }
        }

    }
}
